// Copyright 2010 Alexandre Tristan St-Cyr <tristan.stcyr@gmail.com>

package com.codeplex.loadjava;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;



public class JavaLoaderCli {
	
	private static Logger logger = Logger.getLogger(JavaLoaderCli.class.getCanonicalName());
	
	private static final ISQLConnectionFactory connectionFactory = new SQLServerConnectionFactory();
	
	public static void main(String[] args)
	{	
		printLogo();
		IJavaLoaderOptions options = JavaLoaderOptions.create(args);
		if (options == null) {
			System.exit(-1);
		}
		
		JavaLoaderCli.setupLogging();
		JavaLoaderCli cli = new JavaLoaderCli();
		cli.run(options);
	}
	
	private static void printLogo()
	{
		System.out.println("Java Loader");
		System.out.println("Copyright Alexandre Tristan St-Cyr. All rights reserved.\n");
	}
	
	public void run(IJavaLoaderOptions options) {
		
		Connection connection = null;
		try {
			connection = connectionFactory.createConnection(
					options.getServer(), 
					options.getDatabaseName(), 
					options.getUsername(), 
					options.getPassword());
			
			connection.setAutoCommit(false);
			long folderId = new Repository(connection).getFolderId(options.getTargetFolder());
			
			IJavaLoaderSettings settings = new JavaLoaderSettings(connection, folderId, options);
			
			JavaLoader loader = new JavaLoader(settings);
			loader.load();
			connection.commit();
		}
		catch(ClassNotFoundException e) {
			logger.log(Level.SEVERE, "The database driver could not be found", e);
		} catch (SQLException e) {
			logger.log(Level.SEVERE, "A database error occured", e);
		}
		catch(Throwable e) {
			logger.log(Level.SEVERE, "An unexpected error occured", e);
		}
		finally {
			try {
				if (connection != null) {
					connection.close();
				}
			}
			catch(SQLException e) {
				logger.log(Level.SEVERE, "An error occured while trying to close the connection", e);
			}
		}
	}
	
	private static void setupLogging()
	{
		Logger rootLogger = Logger.getLogger("");
		for(Handler handler : rootLogger.getHandlers()) {
			rootLogger.removeHandler(handler);
		}
		rootLogger.addHandler(new LoggingHandler());
	}
}